package com.daniel.mi.converter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.daniel.mi.dto.UsersDto;
import com.daniel.mi.entity.UsersEntity;
import com.daniel.mi.query.UsersQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * @Author zengneng46764
 * @Date 2024/3/6 22:29
 * @Since 1.0.0.0
 * @description: 用户信息转换器
 */
@Component
public class UsersConverter implements QueryDtoEntityConverter<UsersQuery, UsersDto, UsersEntity>{
    @Override
    public QueryWrapper<UsersEntity> fromQueryToWrapper(UsersQuery query) {
        QueryWrapper<UsersEntity> queryWrapper = new QueryWrapper();
        if(!StringUtils.isBlank(query.getUserAccount())){
            queryWrapper.eq("user_account", query.getUserAccount());
        }
        if(!StringUtils.isBlank(query.getUserCode())){
            queryWrapper.eq("user_code", query.getUserCode());
        }
        if(!StringUtils.isBlank(query.getUserName())){
            queryWrapper.eq("user_name", query.getUserName());
        }
        return queryWrapper;
    }

    @Override
    public UsersEntity fromDtoToEntity(UsersDto dto) {
        final UsersEntity entity = new UsersEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setGmtCreate(LocalDateTime.parse(Optional.ofNullable(dto.getGmtCreate()).orElse(LocalDateTime.now().toString()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        entity.setGmtModify(LocalDateTime.parse(Optional.ofNullable(dto.getGmtModify()).orElse(LocalDateTime.now().toString()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return entity;
    }

    @Override
    public UsersDto fromEntityToDto(UsersEntity entity) {
        final UsersDto dto = new UsersDto();
        BeanUtils.copyProperties(entity, dto);
        dto.setGmtCreate(Optional.ofNullable(entity.getGmtCreate()).orElse(LocalDateTime.now()).toString());
        dto.setGmtModify(Optional.ofNullable(entity.getGmtModify()).orElse(LocalDateTime.now()).toString());
        return dto;
    }
}
